import logging
import time


class LogInfo:
    def __init__(self,name='yui'):
        # 实例化对象
        self.logger = logging.getLogger(name)

    def set_message(self, level, msg):
        global fh, ch
        try:
            str_now = time.strftime('%Y-%m-%d')  # 创建时间
            fh = logging.FileHandler('../../log/auto_' + str_now + '.log')  # 创建文件句柄
            ch = logging.StreamHandler()  # 控制台
            # 格式化输出
            fm = logging.Formatter('%(name)s-%(asctime)s-%(levelname)s-%(message)s')

            fh.setFormatter(fm)  # 文件设置格式
            ch.setFormatter(fm)  # 控制台输出设置格式
            self.logger.addHandler(fh)  # 文件句柄，加入logger对象
            self.logger.addHandler(ch)  # 控制台句柄，加入logger对象
            # 设置打印级别
            self.logger.setLevel(logging.DEBUG)
            # 级别转换为小写，设置不同情况打印消息
            if level.lower() == 'debug':
                self.logger.debug(msg)
            elif level.lower() == 'info':
                self.logger.info(msg)
            elif level.lower() == 'warning':
                self.logger.warning(msg)
            elif level.lower() == 'error':  # 打印堆栈信息
                self.logger.error(msg, exc_info=True, stack_info=True)
            elif level.lower() == 'critical':
                self.logger.critical(msg, exc_info=True, stack_info=True)
            else:
                print('日志级别错误！')
            self.logger.removeHandler(ch)  # 移除控制台对象
            self.logger.removeHandler(fh)  # 移除文件对象
        except Exception as e:
            print(e, '日志操作异常')
        finally:
            ch.close()  # 关闭控制台句柄
            fh.close()  # 关闭文件句柄


# lg = LogInfo()
# lg.set_message('error','debug msg')
